package cn.westv.scps.task;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.westv.scps.connTools.ProxyConnExec;
import cn.westv.scps.constant.ConfigCodeConstant;
import cn.westv.scps.constant.DBconstant;
import cn.westv.scps.constant.SmsTplCodeConstant;
import cn.westv.scps.domain.AreaSeverEntity;
import cn.westv.scps.domain.SmsTemplateEntity;
import cn.westv.scps.domain.SysConfig;
import cn.westv.scps.mqtt.PushCallback;
import cn.westv.scps.service.areaserver.IAreaServerService;
import cn.westv.scps.service.sms.template.ISmsTemplateService;
import cn.westv.scps.service.sys.config.ISysConfigService;
import cn.westv.scps.utils.SpringContextUtil;
import cn.westv.scps.weather.WeatherTools;
import cn.westv.scps.web.utils.SendSmsTools;

/**
 * CRON表达式 含义<br>
 * "0 0 12 * * ?" 每天中午十二点触发<br>
 * "0 15 10 ? * *" 每天早上10：15触发<br>
 * "0 15 10 * * ?" 每天早上10：15触发<br>
 * "0 15 10 * * ? *" 每天早上10：15触发 <br>
 * "0 15 10 * * ? 2005" 2005年的每天早上10：15触发<br>
 * "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发<br>
 * "0 0/5 14 * * ?" 每天从下午2点开始到2：55分结束每5分钟一次触发 <br>
 * "0 0/5 14,18 * * ?" 每天的下午2点至2：55和6点至6点55分两个时间段内每5分钟一次触发<br>
 * "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发<br>
 * "0 10,44 14 ? 3 WED" 三月的每周三的14：10和14：44触发 <br>
 * "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10：15触发<br>
 */
@Component
public class TimedTask {
	public Logger log = Logger.getLogger(TimedTask.class);

	public TimedTask() {
		super();
		log.info("定时任务启动成功.....");
	}

	/**
	 * 这是每天零点初始化短信发送限制次数的任务
	 * 
	 * @throws Exception
	 */
	@Scheduled(cron = "00 00 00 * * ?") // 每天00:00:00
	public void initSmsSendRestrict() throws Exception {// 定时器的任务方法不能有返回值
		Map mobileSendAlarmCountMap = SendSmsTools.mobileSendAlarmCountMap;
		mobileSendAlarmCountMap.clear();// 用户每天发送（告警）信息的次数，清零
		log.info("用户每天发送【告警】信息的次数，清零!");
		Map<String, Integer> visitorSendSmsCountMap = SendSmsTools.visitorLoginSendSmsCountMap;
		visitorSendSmsCountMap.clear();// 每天（游客登录）时发送短信验证的次数限制，清零
		log.info("每天【游客登录】时发送短信验证的次数限制，清零!");
		Map<String, Map<String, Integer>> mobileSendVerificationCountMap = SendSmsTools.mobileSendVerificationCountMap;
		mobileSendVerificationCountMap.clear();
		log.info("每天用户发送验证短信的次数限制，清零!");
	}

	/**
	 * 清除Mqtt数据集合，每周一清除一次
	 * 
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@Scheduled(cron = "00 00 00 ? * MON") // 每逢周一执行
	public void clearMqttMsgSetData() throws FileNotFoundException, IOException {
		PushCallback.RWmqttMsgSetFile(null, PushCallback.getMqttMsgFile(), "write");
		log.info("清除Mqtt去重文件数据");
		PushCallback.mqttMsgSet.clear();
		log.info("清除mqtt数据集合!");
	}

//	@Scheduled(cron = "00 00 0/1 ? * *") // 每小时执行一次
	public void refreshWeather() throws Exception {
		WeatherTools wt = new WeatherTools();
		wt.refreshWeather();// 刷新天气集合
		log.info("刷新了一次天气！");

	}

	/**
	 * 10分钟获取一次服务器的公钥，如果服务器连接失败，则进行标记
	 * 
	 * @throws Exception
	 */
	@Scheduled(cron = "00 0/10 * ? * *") // 每十分钟
	public void refreshPublicKey() throws Exception {
		IAreaServerService areaServerService = (IAreaServerService) SpringContextUtil.getBean("areaServerServiceImpl");
		ISysConfigService sysConfigService = (ISysConfigService) SpringContextUtil.getBean("sysConfigServiceImpl");
		ISmsTemplateService smsTemplateService = (ISmsTemplateService) SpringContextUtil
				.getBean("smsTemplateServiceImpl");
		List<AreaSeverEntity> serverlist = areaServerService.find("from AreaSeverEntity", AreaSeverEntity.class, null);
		for (AreaSeverEntity areaSeverEntity : serverlist) {
			try {
				ProxyConnExec.getPublicKeyBySNcode(areaSeverEntity);
				areaSeverEntity.setDone(DBconstant.NORMAL_SERVER);
			} catch (Exception e) {
				// 记录日志---------------
				ByteArrayOutputStream out = null;
				try {
					out = new ByteArrayOutputStream();
					PrintStream s = new PrintStream(out);
					e.printStackTrace(s);
					String string = new String(out.toByteArray());
					log.error(string);
					log.debug(string);
					log.error(areaSeverEntity.getContextPath() + " 服务器无法连接！");
				} catch (Exception e1) {
					e1.printStackTrace();
				} finally {
					if (out != null)
						out.close();
				}
				// 记录日志---------------
				areaSeverEntity.setDone(DBconstant.DONE_SERVER);// 修改状态
				SysConfig isSms = sysConfigService.findByCode(ConfigCodeConstant.SERVER_ERR_IS_SMS);
				if (isSms != null && isSms.getValue().toUpperCase().equals("YES")) {
					// 发送短信---------------
					SendSmsTools sst = new SendSmsTools();
					SysConfig sysConfig = sysConfigService.findByCode(ConfigCodeConstant.SERVER_ERR_INFORM_MOBILE);
					String value = sysConfig.getValue();
					String[] mobileArr = value.split(",");
					SmsTemplateEntity smsTpl = smsTemplateService.findByCode(SmsTplCodeConstant.SERVER_ERR_INFORM);
					String content = smsTpl.getContent();
					String text = content.replaceAll("#server#", areaSeverEntity.getServerName());
					sst.sendBatchMessage(mobileArr, text);// 发送短信，并记录短信
					// 发送短信---------------
				}
			}
			areaServerService.saveOrUpdate(areaSeverEntity);
		}

	}

}
